package main

import (
	"flag"
	"fmt"
	"net"
	"time"
)

var (
	c = flag.Bool("c", false, "client")
	s = flag.Bool("s", false, "server")
)

var (
	times = 10
	port  = "19880"
)

func C() {
	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:"+port)
	if err != nil {
		panic(err)
	}
	var clt net.Conn
	clt, err = net.DialUDP("udp", nil, addr)
	if err != nil {
		panic(err)
	}
	for i := 0; i < times; i++ {
		data := fmt.Sprintf("%d:%s\n", i, "Hello")
		fmt.Print("Send:", data)
		time.Sleep(time.Second)
		_, err := clt.Write([]byte(data))
		if err != nil {
			fmt.Println("ERROR:", err)
		}
	}
}

func S() {
	laddr, err := net.ResolveUDPAddr("udp", ":"+port)
	if err != nil {
		panic(err)
	}
	var svr net.Conn
	svr, err = net.ListenUDP("udp", laddr)
	if err != nil {
		panic(err)
	}
	var buf [1024]byte
	for {
		n, err := svr.Read(buf[:])
		if err != nil {
			panic(err)
		}
		fmt.Printf(string(buf[:n]))
	}
}

func main() {
	flag.Parse()
	switch {
	case *c:
		C()
		return
	case *s:
		S()
		return
	}
}
